package com.bookshop.controller;

import com.bookshop.bean.AdminBean;
import com.bookshop.bean.ResultBean;
import com.bookshop.dao.AdminDao;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
public class AdminController {
    @Resource
    private AdminDao adminDao;
    /**
     * 登录
     * @param account
     * @param pass
     * @return
     */
    @RequestMapping("/login")
    public ResultBean login(String account,String pass,HttpSession session){
        ResultBean result = new ResultBean();
        AdminBean admin = adminDao.selectByAccountAndPass(account, pass);
        if(admin == null){
            result.setCode(-1);
            result.setMsg("账号或密码错误");
        }else{
            result.setCode(1);
            result.setMsg("登录成功");
            result.setData(admin);
            session.setAttribute("admin",admin);
        }
        return result;
    }

    @RequestMapping("/logout")
    public ResultBean logout(HttpSession session){
        ResultBean result = new ResultBean();
        session.invalidate();
        result.setCode(1);
        result.setMsg("退出成功");

        return result;
    }

    /**
     * 实现修改
     * @param oldPass
     * @param newPass
     * @param confirmPass
     * @return
     */
    @RequestMapping("/modify_pass")
    public ResultBean modifyPass(String oldPass,String newPass,String confirmPass,HttpSession session){
        ResultBean result = new ResultBean();

        AdminBean admin = (AdminBean) session.getAttribute("admin");

        AdminBean adminTemp = adminDao.selectByAccountAndPass(admin.getAccount(), oldPass);
        if(adminTemp == null){
            result.setCode(-1);
            result.setMsg("原始密码不正确");
            return result;
        }
        if(adminDao.updatePass(newPass,admin.getAccount()) == 1){
            result.setCode(1);
            result.setMsg("密码修改成功");
        }else{
            result.setCode(-1);
            result.setMsg("密码修改失败");
        }
        return result;
    }


}
